package cn.cnf.controller;

import cn.cnf.common.Result;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * @author ZhuMeiYi
 * @date 2021/1/30 16:34
 * @description
 */
@RestController
public class CustomErrorController implements ErrorController {
    private static final String PATH = "/error";

    @Autowired
    private ErrorAttributes errorAttributes;

    static String EXCEPTION = "exception";
    static String ERROR = "error";
    static String FORBIDDEN = "Forbidden";

    @RequestMapping(value = PATH)
    Result error(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> errorMap = getErrorAttributes(request);

        if (errorMap.containsKey(EXCEPTION)){
            String exception = errorMap.get(EXCEPTION).toString();
            if (exception.equals(ExpiredJwtException.class.getName())){
                return Result.warn("token已过期");
            }
            else if (exception.equals(MalformedJwtException.class.getName())){
                return Result.warn("token不合法");
            }
        }else if (errorMap.containsKey(ERROR)){
            String error = errorMap.get(ERROR).toString();
            if (FORBIDDEN.equals(error)){
                return Result.warn("请求被拒绝,请确认权限");
            }
        }


        //定义返回格式
        Result d= new Result();
        d.setMessage(Objects.requireNonNull(errorMap.get("message")).toString());
        d.setCode(Integer.valueOf(Objects.requireNonNull(errorMap.get("status")).toString()));
        response.setStatus(HttpServletResponse.SC_OK);
        return d;
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
        WebRequest requestAttributes = new ServletWebRequest(request);
        return errorAttributes.getErrorAttributes(requestAttributes,false);
    }

}